"""Follow-up reminder model."""

from __future__ import annotations

from datetime import datetime
from typing import TYPE_CHECKING

from sqlalchemy import DateTime, ForeignKey, Integer, String, Text
from sqlalchemy.orm import Mapped, mapped_column, relationship

from ..db.base_class import Base
from .base import TimestampMixin

if TYPE_CHECKING:
    from .lead import Lead
    from .user import User
    from .visitor_sheet import VisitorSheet


class FollowUpReminder(Base, TimestampMixin):
    """跟进提醒模型."""

    __tablename__ = "follow_up_reminders"

    id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
    lead_id: Mapped[int] = mapped_column(
        ForeignKey("leads.id", ondelete="CASCADE"), nullable=False, index=True
    )
    visitor_sheet_id: Mapped[int | None] = mapped_column(
        ForeignKey("visitor_sheets.id", ondelete="SET NULL"), nullable=True
    )
    reminder_type: Mapped[str] = mapped_column(
        String(50), nullable=False
    )  # auto/manual
    trigger_reason: Mapped[str | None] = mapped_column(
        String(200), nullable=True
    )  # 触发原因
    reminder_time: Mapped[datetime] = mapped_column(
        DateTime, nullable=False, index=True
    )  # 提醒时间
    status: Mapped[str] = mapped_column(
        String(20), nullable=False, default="pending", index=True
    )  # pending/sent/completed/cancelled
    assigned_to: Mapped[int] = mapped_column(
        ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True
    )  # 分配给谁
    notes: Mapped[str | None] = mapped_column(Text, nullable=True)
    sent_at: Mapped[datetime | None] = mapped_column(
        DateTime, nullable=True
    )  # 邮件发送时间
    completed_at: Mapped[datetime | None] = mapped_column(
        DateTime, nullable=True
    )  # 完成时间

    # Relationships
    lead: Mapped[Lead] = relationship("Lead", back_populates="reminders")
    visitor_sheet: Mapped[VisitorSheet | None] = relationship(
        "VisitorSheet", back_populates="reminders"
    )
    assignee: Mapped[User] = relationship("User", foreign_keys=[assigned_to])

    def __repr__(self) -> str:
        """String representation."""
        return f"<FollowUpReminder(id={self.id}, lead_id={self.lead_id}, status={self.status})>"
